package top.honlnk.czuan.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.honlnk.czuan.common.config.ConstantConfig;
import top.honlnk.czuan.common.exception.CustomException;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class AliOSSUtil {

    @Autowired
    private ConstantConfig constantConfig;

    // 上传百度词典的查询结果文件
    public String uploadDictFile(@NotNull String word, @NotNull JSONObject dictData) {

        String fileUrl  = "";

        if (dictData.isEmpty()) {
            return fileUrl;
        }

        try {
            OSS ossClient = new OSSClientBuilder().build(
                    constantConfig.getAliOssEndpoint(),
                    constantConfig.getAliOssAccessKeyId(),
                    constantConfig.getAliOssAccessKeySecret());

            // 循环dictObj获取他的键名
            // 定义百度文本翻译词典版在OSS中的路径
            String dictPath = "dict/json/baidu/";

            // 生成文件名
            String objectName = dictPath + word + "--" + IdUtil.fastSimpleUUID() + ".json";

            // 获取值
            // 将JSON对象转为格式化的字符串，并创建一个字节数组输入流
            String dictObjStr = JSONUtil.toJsonStr(dictData);
            byte[] dictObjBytes = dictObjStr.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(dictObjBytes);

            // 创建PutObjectRequest对象
            String bucketName = constantConfig.getAliOssBucketName();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            ossClient.putObject(putObjectRequest);

            // 拼接文件的可公开访问URL
            fileUrl = constantConfig.getAliOssPublicAccessDomain() + "/" + objectName;
        } catch (OSSException | ClientException e) {
            log.error("阿里云OSS上传文件失败", e);
        }
        return fileUrl;
    }

    // 上传百度词典的语音文件
    public Map<String, String> uploadTtsFile(@NotNull String word, JSONObject ttsData) {
        Map<String,String> fileUrl = new HashMap<>();

        OSS ossClient = new OSSClientBuilder().build(
                constantConfig.getAliOssEndpoint(),
                constantConfig.getAliOssAccessKeyId(),
                constantConfig.getAliOssAccessKeySecret());
        // 定义百度翻译音频信息在OSS中的路径
        String dictPath = "dict/audio/baidu/";
        String dstObjectName = dictPath + word + "--zh--" + IdUtil.fastSimpleUUID() + ".mp3";
        String srcObjectName = dictPath + word + "--en--" + IdUtil.fastSimpleUUID() + ".mp3";
        String bucketName = constantConfig.getAliOssBucketName();

        // 获取值，并将其转为字节数组输入流

        String dstTtsFileBase64 = ttsData.getStr("dstTtsFileBase64");
        if (!dstTtsFileBase64.isEmpty()) {
            byte[] dstTtsFileBytes = Base64.decode(dstTtsFileBase64);
            ByteArrayInputStream dstTtsFileInputStream = new ByteArrayInputStream(dstTtsFileBytes);

            // 创建PutObjectRequest对象，并将数据存入OSS
            PutObjectRequest dstTutObjectRequest = new PutObjectRequest(bucketName, dstObjectName, dstTtsFileInputStream);
            ossClient.putObject(dstTutObjectRequest);

            // 拼接文件的可公开访问URL
            String dstFileUrl = constantConfig.getAliOssPublicAccessDomain() + "/" + dstObjectName;
            fileUrl.put("zhFileUrl",dstFileUrl);
        } else {
            fileUrl.put("zhFileUrl", "");
        }

        String srcTtsFileBase64 = ttsData.getStr("srcTtsFileBase64");
        if (!srcTtsFileBase64.isEmpty()) {
            byte[] srcTtsFileBytes = Base64.decode(srcTtsFileBase64);
            ByteArrayInputStream srcTtsFileInputStream = new ByteArrayInputStream(srcTtsFileBytes);

            // 创建PutObjectRequest对象，并将数据存入OSS
            PutObjectRequest srcTutObjectRequest = new PutObjectRequest(bucketName, srcObjectName, srcTtsFileInputStream);
            ossClient.putObject(srcTutObjectRequest);

            // 拼接文件的可公开访问URL
            String srcFileUrl = constantConfig.getAliOssPublicAccessDomain() + "/" + srcObjectName;
            fileUrl.put("enFileUrl",srcFileUrl);
        } else {
            fileUrl.put("enFileUrl", "");
        }


        // 上传音频文件到OSS
        return fileUrl;
    }

    // 获取百度词典的查询结果文件
    public JSONObject getDictFile(@NotNull String fileUrl) {
        String FileString = HttpUtil.get(fileUrl);
        if (FileString == null || FileString.isBlank()) {
            throw new CustomException("获取百度词典查询结果文件失败，请确认您的地址正确");
        }
        return JSONUtil.parseObj(FileString);
    }

    // 上传AI讲解单词的Markdown文件
    public String uploadMarkdownFile(@NotNull String markdownFileData, String word) {
        try {
            OSS ossClient = new OSSClientBuilder().build(
                    constantConfig.getAliOssEndpoint(),
                    constantConfig.getAliOssAccessKeyId(),
                    constantConfig.getAliOssAccessKeySecret());

            // 定义AI讲解单词的Markdown文件在OSS中的路径
            String dictPath = "dict/markdown/ai-explain/";
            // 生成文件名
            String objectName = dictPath + word + "--" + IdUtil.fastSimpleUUID() + ".md";

            byte[] dictObjBytes = markdownFileData.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(dictObjBytes);

            // 创建PutObjectRequest对象
            String bucketName = constantConfig.getAliOssBucketName();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            ossClient.putObject(putObjectRequest);

            return constantConfig.getAliOssPublicAccessDomain() + "/" + objectName;
        } catch (Exception e) {
            log.error("阿里云OSS上传文件失败", e);
        }
        return "";
    }
}
